const { toTryCatch } = require("../../utils")

module.exports = {
    getCamerasDao: function (req, data) {
        return toTryCatch(() => req.Model.find(data))
    },
    startRTSPStreamDao: async function (app, req, data) {
        const { startRTSPStream } = require('../../utils/rtsp-stream')(app)
        const { checkPortInUse } = require('../../utils')
        const isCheckPortInUse = await checkPortInUse(data.wsPort)
        if (isCheckPortInUse) {
            const res = await startRTSPStream(data)
            if (res.type === 'success') {
                console.log(`开启${data.name}的RTSP流成功！ WebSocket端口号为：${data.wsPort}`);
                return res
            }
        } else {
            console.log(`端口${data.wsPort}已被占用，尝试使用端口${data.wsPort - 1}！`);
            data.wsPort -= 1;
            return await this.startRTSPStreamDao(app, req, data)
        }
    },
    closeRTSPStreamDao: async function (app, req, name) {
        const { stopRTSPStream } = require('../../utils/rtsp-stream')(app);
        const res = await stopRTSPStream(name);
        if (res.type === 'success') {
            console.log(`关闭${name}的RTSP流成功！`);
            return { type: 'success', message: `关闭${name}的RTSP流成功！` }
        } else {
            return { type: 'error', message: `关闭${name}的RTSP流失败！` }
        }
    },
    snapshotRTSPStreamDao: async function (app, req, data) {
        const { captureRTSPSnapshot } = require('../../utils/rtsp-stream')(app)
        const filename = `${data.name}.${data.type}`;
        const streamQueue = app.get('streamQueue');
        const stream = streamQueue.find((stream) => stream.name === data.cameraName)
        captureRTSPSnapshot(stream, data.path, filename).then((res) => {
            saveFileToDB(data)
        })
    },
    recordRTSPStreamDao: async function (app, req, data) {
        const { recordRTSPStream } = require('../../utils/rtsp-stream')(app)
        const streamQueue = app.get('streamQueue');
        const stream = streamQueue.find((stream) => stream.name === data.cameraName)
        recordRTSPStream(stream, data).then((res) => {
            setTimeout(() => {
                saveFileToDB(data)
                return res
            }, (data.duration + 2) * 1000);
        })
    }
}
function saveFileToDB(data) {
    const File = require('../../models/File')
    const copyData = JSON.parse(JSON.stringify(data))
    copyData.extname = copyData.type
    copyData.type = 'file'
    delete copyData.cameraName
    File.create(copyData)
}
